package com.example.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.example.shop.LoginActivity;
import com.example.shop.R;
import com.example.shop.User;
import com.example.utils.UserDataUtils;

import java.util.Objects;

import jp.wasabeef.glide.transformations.BlurTransformation;
import jp.wasabeef.glide.transformations.CropCircleTransformation;

import static android.app.Activity.RESULT_OK;
import static android.content.Context.MODE_PRIVATE;

public class FragmentUser extends Fragment {
    private TextView text_userId, nickname, sex, signature;
    private ImageView iv_Photo;
    private ImageView iv_background;
    View view;
    long firstTime = 0;
    public String userId;
    Intent data = new Intent();
    SharedPreferences sharedPreferences;
    int image_x, image_y;
    Integer[][] image = {{R.drawable.h1, R.drawable.h2, R.drawable.h3},
            {R.drawable.h4, R.drawable.h5, R.drawable.h6},
            {R.drawable.h7, R.drawable.h8, R.drawable.h9}};


    @SuppressLint("InflateParams")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_user, null);
        //show userId
        text_userId = view.findViewById(R.id.userId);
        SharedPreferences sharedPreferences = Objects.requireNonNull(getActivity()).getSharedPreferences("name", 0);  /*获取名称为name的sharedPreferences*/
        userId = sharedPreferences.getString("name", "");  /*get id*/
        text_userId.setText(String.format("欢迎你：%s", userId));

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        iv_Photo = view.findViewById(R.id.iv_photo);
        iv_Photo.setOnClickListener(v -> show_image_dialog());

        iv_background = view.findViewById(R.id.iv_background);
        nickname = view.findViewById(R.id.nickname);
        sex = view.findViewById(R.id.sex);
        signature = view.findViewById(R.id.signature);

        RelativeLayout rl_username = view.findViewById(R.id.rl_nickname);
        rl_username.setOnClickListener(view -> show_nicknameDialog());

        RelativeLayout rl_sex = view.findViewById(R.id.rl_sex);
        rl_sex.setOnClickListener(view -> show_sexDialog());

        RelativeLayout rl_signature = view.findViewById(R.id.rl_signature);
        rl_signature.setOnClickListener(view -> show_signatureDialog());

        RelativeLayout rl_version = view.findViewById(R.id.rl_version);
        rl_version.setOnClickListener(view -> Toast.makeText(getActivity(), "已是最新版本", Toast.LENGTH_SHORT).show());

        RelativeLayout rl_Exchange = view.findViewById(R.id.rl_exchange);
        rl_Exchange.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setClass(Objects.requireNonNull(getContext()), LoginActivity.class);
            sharedPreferences = getContext().getSharedPreferences("data", MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.clear();
            editor.apply();
            startActivity(intent);
            Objects.requireNonNull(getActivity()).finish();
        });

        RelativeLayout rl_quit = view.findViewById(R.id.rl_quit);
        rl_quit.setOnClickListener(v -> {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime < 2000) {
                Objects.requireNonNull(getActivity()).finish();
            } else {
                Toast.makeText(getContext(), "再点一次,注销登录", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            }
        });

        //head
        TextView tv_main_title = view.findViewById(R.id.tv_main_title);
        tv_main_title.setText("个人中心");
        RelativeLayout rl_title_bar = view.findViewById(R.id.title_bar);
        rl_title_bar.setBackgroundColor(Color.rgb(255, 165, 0));

        //go back
        ImageView goBack = view.findViewById(R.id.iv_back);
        goBack.setVisibility(View.GONE);

        initData();
        showImage();
    }

    public void initData() {
        User user;
        user = UserDataUtils.getInstance(getActivity()).getUserInfo(userId);
        if (user == null) {
            user = new User();
            user.userID = userId;
            user.nickName = "张三";
            user.sex = "男";
            user.signature = "张三的传奇一生";
            //save  default user data
            UserDataUtils.getInstance(getActivity()).saveUserInfo(user);
        }
        showInf(user);
    }

    private void showInf(User user) {
        nickname.setText(user.nickName);
        text_userId.setText(user.userID);
        sex.setText(user.sex);
        signature.setText(user.signature);
    }

    public void showImage() {
        SharedPreferences s = Objects.requireNonNull(getContext()).getSharedPreferences("image_pos", Context.MODE_PRIVATE);
        image_x = s.getInt("image_x", 0);
        image_y = s.getInt("image_y", 0);
        Glide.with(this).load(image[image_x][image_y]).bitmapTransform(new BlurTransformation(Objects.requireNonNull(getActivity()), 25), new CenterCrop(getActivity())).into(iv_background);
        Glide.with(this).load(image[image_x][image_y]).bitmapTransform(new CropCircleTransformation(getActivity())).into(iv_Photo);
    }

    @SuppressLint("InflateParams")
    public void show_image_dialog() {
        View dialog_image = LayoutInflater.from(getContext()).inflate(R.layout.dialog_photo, null);
        RelativeLayout rl_title_bar = dialog_image.findViewById(R.id.title_bar);
        rl_title_bar.setBackgroundColor(Color.rgb(255, 165, 0));
        TextView title = dialog_image.findViewById(R.id.tv_main_title);
        title.setText("选择您的头像");
        ImageView goBack = dialog_image.findViewById(R.id.iv_back);
        GridLayout gl = dialog_image.findViewById(R.id.gl);

        AlertDialog.Builder ab = new AlertDialog.Builder(Objects.requireNonNull(getActivity()));
        ab.setCancelable(false);
        AlertDialog alertDialog_change_image = ab.create();
        alertDialog_change_image.setView(dialog_image);

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                ImageView iv = new ImageView(getContext());
                Glide.with(this).load(image[i][j]).bitmapTransform(new CropCircleTransformation(getActivity())).into(iv);
                final int image_x = i;
                final int image_y = j;
                iv.setOnClickListener(v -> {
                    SharedPreferences s = Objects.requireNonNull(getContext()).getSharedPreferences("image_pos", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = s.edit();
                    editor.putInt("image_x", image_x);
                    editor.putInt("image_y", image_y);
                    editor.apply();
                    Glide.with(this).load(image[image_x][image_y]).bitmapTransform(new BlurTransformation(Objects.requireNonNull(getActivity()), 25), new CenterCrop(getActivity())).into(iv_background);
                    Glide.with(this).load(image[image_x][image_y]).bitmapTransform(new CropCircleTransformation(getActivity())).into(iv_Photo);
                    alertDialog_change_image.dismiss();
                });
                GridLayout.Spec rowSpec = GridLayout.spec(i);
                GridLayout.Spec columnSpec = GridLayout.spec(j);
                GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowSpec, columnSpec);
                params.width = 300;
                params.height = 300;
                params.setGravity(Gravity.CENTER);
                gl.addView(iv, params);

            }
        }

        goBack.setOnClickListener(view -> alertDialog_change_image.dismiss());

        alertDialog_change_image.show();
    }

    @SuppressLint("InflateParams")
    private void show_nicknameDialog() {
        View dialog_nickname = LayoutInflater.from(getContext()).inflate(R.layout.nc_dialog, null);
        RelativeLayout rl_title_bar = dialog_nickname.findViewById(R.id.title_bar);
        rl_title_bar.setBackgroundColor(Color.rgb(255, 165, 0));
        TextView title = dialog_nickname.findViewById(R.id.tv_main_title);
        title.setText("昵称修改");

        final EditText edit_name = dialog_nickname.findViewById(R.id.name_edit);
        Button yes = dialog_nickname.findViewById(R.id.yes);
        Button no = dialog_nickname.findViewById(R.id.no);
        ImageView goBack = dialog_nickname.findViewById(R.id.iv_back);

        AlertDialog.Builder ab = new AlertDialog.Builder(Objects.requireNonNull(getActivity()));
        ab.setCancelable(false);
        AlertDialog alertDialog_change_nickname = ab.create();
        alertDialog_change_nickname.setView(dialog_nickname);

        yes.setOnClickListener(view -> {
            String new_nickname = edit_name.getText().toString();
            String new_info;
            if (!TextUtils.isEmpty(new_nickname)) {
                data.putExtra("nickName", new_nickname);
                Objects.requireNonNull(getActivity()).setResult(RESULT_OK, data);
                if (data != null) {
                    new_info = data.getStringExtra("nickName");
                    if (TextUtils.isEmpty(new_info) || new_info == null) {
                        return;
                    }
                    nickname.setText(new_nickname);
                    UserDataUtils.getInstance(getActivity()).updateUserInfo("nickName", new_info, userId);
                    Toast.makeText(getActivity(), "保存成功！", Toast.LENGTH_SHORT).show();
                    alertDialog_change_nickname.dismiss();
                }
            } else {
                Toast.makeText(getActivity(), "请输入昵称!", Toast.LENGTH_SHORT).show();
            }
        });
        no.setOnClickListener(view -> alertDialog_change_nickname.dismiss());
        goBack.setOnClickListener(view -> alertDialog_change_nickname.dismiss());


        alertDialog_change_nickname.show();
    }

    @SuppressLint("InflateParams")
    private void show_sexDialog() {
        View dialog_sex = LayoutInflater.from(getContext()).inflate(R.layout.sex_dialog, null);
        RelativeLayout rl_title_bar = dialog_sex.findViewById(R.id.title_bar);
        rl_title_bar.setBackgroundColor(Color.rgb(255, 165, 0));
        TextView title = dialog_sex.findViewById(R.id.tv_main_title);
        title.setText("性别选择");
        ImageView goBack = dialog_sex.findViewById(R.id.iv_back);
        RadioGroup radioGroup = dialog_sex.findViewById(R.id.radio);
        final Button bt_man = dialog_sex.findViewById(R.id.man);
        final Button bt_woman = dialog_sex.findViewById(R.id.woman);
        final Button bt_null = dialog_sex.findViewById(R.id.nullsex);

        AlertDialog.Builder ab = new AlertDialog.Builder(Objects.requireNonNull(getActivity()));
        ab.setCancelable(false);
        AlertDialog alertDialog_change_sex = ab.create();
        alertDialog_change_sex.setView(dialog_sex);

        radioGroup.setOnCheckedChangeListener((radioGroup1, i) -> {
            String man = bt_man.getText().toString();
            String woman = bt_woman.getText().toString();
            String secret = bt_null.getText().toString();
            if (i == R.id.man) {
                sex.setText(man);
                UserDataUtils.getInstance(getActivity()).updateUserInfo("sex", man, userId);
                alertDialog_change_sex.dismiss();
            } else if (i == R.id.woman) {
                sex.setText(woman);
                UserDataUtils.getInstance(getActivity()).updateUserInfo("sex", woman, userId);
                alertDialog_change_sex.dismiss();
            } else {
                sex.setText(secret);
                UserDataUtils.getInstance(getActivity()).updateUserInfo("sex", secret, userId);
                alertDialog_change_sex.dismiss();
            }
        });

        goBack.setOnClickListener(view -> alertDialog_change_sex.dismiss());

        alertDialog_change_sex.show();
    }

    @SuppressLint("InflateParams")
    private void show_signatureDialog() {
        View dialog_signature = LayoutInflater.from(getContext()).inflate(R.layout.signature_dialog, null);
        RelativeLayout rl_title_bar = dialog_signature.findViewById(R.id.title_bar);
        rl_title_bar.setBackgroundColor(Color.rgb(255, 165, 0));
        TextView title = dialog_signature.findViewById(R.id.tv_main_title);
        title.setText("个性签名");
        ImageView goBack = dialog_signature.findViewById(R.id.iv_back);
        Button yes = dialog_signature.findViewById(R.id.yes2);
        Button no = dialog_signature.findViewById(R.id.no2);
        EditText edit_signature = dialog_signature.findViewById(R.id.tv_sg);

        AlertDialog.Builder ab = new AlertDialog.Builder(Objects.requireNonNull(getActivity()));
        ab.setCancelable(false);
        AlertDialog alertDialog_change_signature = ab.create();
        alertDialog_change_signature.setView(dialog_signature);

        yes.setOnClickListener(view -> {
            String csg = edit_signature.getText().toString().trim();
            String new_info;
            if (!TextUtils.isEmpty(csg)) {
                data.putExtra("signature", csg);
                getActivity().setResult(RESULT_OK, data);
                if (data != null) {
                    new_info = data.getStringExtra("signature");
                    if (TextUtils.isEmpty(new_info) || new_info == null) {
                        return;
                    }
                    signature.setText(new_info);
                    UserDataUtils.getInstance(getActivity()).updateUserInfo("signature", new_info, userId);
                }
                Toast.makeText(getActivity(), "保存成功!", Toast.LENGTH_SHORT).show();
                alertDialog_change_signature.dismiss();
            } else
                Toast.makeText(getActivity(), "请输入个性签名!", Toast.LENGTH_SHORT).show();
        });

        no.setOnClickListener(view -> alertDialog_change_signature.dismiss());
        goBack.setOnClickListener(view -> alertDialog_change_signature.dismiss());
        alertDialog_change_signature.show();
    }
}
